import json

from django.core import paginator
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, HttpResponse, HttpResponseRedirect, reverse, redirect
from .models import *
from django.http import JsonResponse
import hashlib, urllib
import urllib.request
from django.views.decorators.csrf import csrf_exempt
from cnnews import settings
from random import randint
import smtplib
from .forms import EditorForm
from .tools import handle_upload_file
from .models import Author
import os
import base64
from django.contrib import auth
from django.contrib.auth import logout, login
from news import models as a_models
from datetime import datetime


def md5_code(str):
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    return md5.hexdigest()



# Create your views here.
# 登录验证
def base(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        if not username:
            msg = '手机号不能为空'
            return render(request, 'news/log.html', locals())
        if not password:
            msg = '密码不能为空'
            return render(request, 'news/log.html', locals())
        if Author.objects.filter(username=username).exists():
            author = Author.objects.get(username=username)
            if author.password == md5_code(password):
                request.session['user'] = username
                return render(request, 'news/base.html', {'author': author})
            else:
                # print(author.password)
                msg = '密码输入错误'
                return render(request, 'news/log.html', locals())
        else:
            msg = '用户不存在'
            return render(request, 'news/log.html', locals())
    return HttpResponse('非法入侵')
    # return render(request, 'news/base.html')


# 注册
def register(request):
    return render(request, 'news/register.html')

# 注册验证
def register_check(request):
    if request.method == "POST":
        print("===========")
        phone = request.POST['phone']
        number = request.POST['number']
        password1 = request.POST['password1']
        password2 = request.POST['password2']
        print(phone, number, password1, password2)
        if not phone:
            msg = '手机号不能为空'
            return render(request, 'news/register.html',locals())
        if  not number:
            msg = '验证码不能为空'
            return render(request, 'news/register.html', locals())
        if not password1 == password2:
            msg = '密码输入不一致,请重新输入!'
            return render(request, 'news/register.html', locals())
        code = request.session['code']
        if number == code:
            author = Author()
            author.username = phone
            author.password = md5_code(password1)
            author.phone_num = phone
            author.save()
            return HttpResponseRedirect(reverse('news:log'))
        else:
            msg = '验证码错误'
            return render(request, 'news/register.html', locals())
    return HttpResponseRedirect(reverse('news:register'))



# 验证码验证
# @csrf_exempt
# def code(request):
#     to_email = request.POST['email']
#     code = randint(1000, 10000)
#     smtpserver = settings.EMAIL_HOST
#     smtp = smtplib.SMTP()  # 创建一个连接
#     smtp.connect(smtpserver)  # 连接发送邮件的服务器
#     smtp.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)  # 登录服务器
#     try:
#         smtp.sendmail(settings.DEFAULT_FROM_EMAIL, to_email, str(code))
#         request.session['code'] = code
#         return JsonResponse({'status': 0, 'status_text':'发送成功'})
#     except:
#         return JsonResponse({'status': 1, 'status_text':'发送失败'})


# 短信验证
@csrf_exempt
def code(request):
    statusStr = {
        '0': '短信发送成功',
        '-1': '参数不全',
        '-2': '服务器空间不支持,请确定支持curl或者fsocket,联系您的空间商解决或者更换空间',
        '30': '密码错误',
        '40': '账号不存在',
        '41': '余额不足',
        '42': '账户已过期',
        '43': 'IP地址限制',
        '50': '内容含有敏感词',
    }

    smsapi = 'http://api.smsbao.com/'
    # 短信平台账号
    user = '13633822725'
    # 短信平台密码
    password = md5_code('13503751894')
    # 要发送的短信内容
    code = randint(1000, 10000)
    # print(code)
    content = code
    # 要发送的短信内容
    phone = request.POST['phone_num']
    data = urllib.parse.urlencode({'u': user, 'p': password, 'm': phone, 'c': content})
    send_url = smsapi + 'sms?' + data
    response = urllib.request.urlopen(send_url)
    the_page = response.read().decode('utf-8')
    request.session['code'] = str(content)

    print(statusStr[the_page])
    print('=====================')
    print('9999')
    data_dict = {
        'status_code': the_page,
        'status_text': statusStr[the_page],
        'yzm': str(code)
    }
    return JsonResponse(data_dict)


# 登录
def log(request):
    return render(request, 'news/log.html')



# 密码修改
def pwd(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        if request.method == "POST":
            password = request.POST['new_pwd1']
            repassword = request.POST['new_pwd2']
            if password == repassword:
                author.password = md5_code(password)
                author.save()
                return render(request,'news/log.html')
            else:
                msg = '您输入的密码不一样!!! '
                return render(request, 'news/cgmm.html', {'msg': msg})
        return HttpResponse('非法入侵!!!')



# 修改密码验证
def pwd_check(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        if request.method == "POST":
            phone_num = request.POST['register_ph']
            # number = request.POST['number1']
            if author.phone_num == phone_num:
            # if not number:
            #     msg = '验证码不能为空'
            #     return render(request, 'news/xgmm.html', locals())
                return render(request, 'news/pwd.html',{'author':author})
            else:
                msg = '您输入的号码不存在'
                return render(request, 'news/xgmm.html', {'msg': msg})
        else:
            return HttpResponse('非法入侵!!!')




# 修改密码
def xgmm(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        return render(request, 'news/xgmm.html',{'author': author})



# 个人资料
def people(request):
    # form = UploadForm()
    username = request.session.get('user', False)
    print(username)
    if username:
        if Author.objects.filter(username=username):
            author = Author.objects.get(username=username)
            return render(request, 'news/people.html', {'author': author})
    return HttpResponse("异常")


# 文件上传
def upload(request):
    print("======================================")
    if request.method == "POST":
        phone = request.POST['phone_num']
        print(phone)
        if Author.objects.filter(phone_num=phone).exists():
            print("++++++++++++++++++++++++")

            author = Author.objects.get(phone_num=phone)
            author.nick_name = request.POST['nick_name']
            author.photo = request.FILES['photo']
            if os.path.exists('phone_num'):
                os.remove('phone_num')
            author.save()
            return render(request, 'news/people.html', {'author': author})
    return HttpResponse("sorry!!!")


# 忘记密码
def forget(request):
    # username = request.session['user']
    # author = Author.objects.get(username=username)
    return render(request, 'news/forget.html')


# 验证忘记密码
def forget_password(request):
    if request.method == "POST":
        phone_num = request.POST['phone']
        print(request.POST)

        if Author.objects.filter(phone_num=phone_num).exists():
            # 如果号码一致,进入重置密码
            author = Author.objects.get(phone_num=phone_num)
            return render(request,'news/chongzhi.html',{'author':author})
        else:
            msg = '您输入的号码不存在'
            return render(request, 'news/forget.html', {'msg':msg})
    return HttpResponse('非法入侵!!!')


# 重置密码
def chongzhi(request):
    if request.method == "POST":
        username = request.POST['username']
        author = Author.objects.get(username = username)

        password = request.POST['new_pwd1']
        repassword = request.POST['new_pwd2']
        if password == repassword:
            author.password = md5_code(password)
            author.save()
            return render(request,'news/log.html')
        else:
            msg = '您输入的密码不一样!!! '
            return render(request, 'news/chongzhi.html', {'msg': msg})
    return HttpResponse('非法入侵!!!')


# 我的会员
def hy(request):
    username = request.session.get('user', default=False)
    if username != False:
        if Author.objects.filter(username=username).exists():
            author = Author.objects.get(username=username)
            pay = Pay.objects.filter(author=author.id)
            consumes_list = author.pay.all()
            page = request.GET.get('page')
            page_yeshu = 10
            contacts = page_aduit(consumes_list, page, page_yeshu)
            return render(request, 'news/hy.html',{'author': author, 'pay':pay, 'contacts':contacts})
    else:
        return redirect('news:hy')



# 会员充值
def hycz(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        return render(request, 'news/hycz.html',{'author':author})
    else:
        return redirect('news:hycz')



# 会员充值验证
def play(request):
    username = request.session.get('user', False)
    if username == False:
        return render(request, 'log.html')
    else:
        author = Author.objects.get(username=username)
        if request.method == 'GET':
            charge = request.GET['money']
            # print('=======================')
            # print(charge)
            # print(type(charge))
            play_choice = request.GET['play_choice']
            money = author.money
            author.money = money + int(charge)
            if author.money >= 10000:
                author.vip = 3
            elif 5000 < author.money < 10000:
                author.vip = 2
            else:
                author.vip = 1
            author.score = author.money * 10
            pay = Pay.objects.create(title="12345",money=charge,author=author)
            author.save()

            if play_choice == 'zfb':
                msg = '您的支付宝账户有一笔' + charge + '的支出,请注意查看!!!'
            else:
                msg = '您的微信账户有一笔' + charge + '的支出,请注意查看!!!'
            vip = str(author.vip)
            info = '尊敬的用户' + author.username + ',您成功充值:' + charge + ',当前vip等级为:' + vip + '级'
            return JsonResponse({'info': info, 'msg': msg})

        else:
            error_info = '添加失败,请检查操作步骤,重新操作!!!'
            return render(request, 'news/hy.html', {'author': author, 'error_info': error_info})



# 我的发布
def fabu(request):

    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        status = request.get_signed_cookie('status', salt='wenyong', default=None)
        article_list = Article.objects.filter(author=author, status=status).values() if status != '0' and status is not None else author.articles.all().values()

        # 分页
        page = request.GET.get('page', False)
        page = page if page != False else 1
        p = Paginator(article_list, 4)
        try:
            article_list1 = p.page(page)
        except PageNotAnInteger:
            article_list1 = p.page(1)
        except EmptyPage:
            article_list1 = p.page(paginator.num_pages)
        status = status if status is not None else '0'
        # print('================================================')
        # print(list(article_list))

        return render(request, 'news/fabu.html', {'status':status, 'article_list1':article_list1,'author': author})
    else:
        # 重定向
        return redirect('news:base')


# 分页
def art_lists(article_list,page, page_num):
    # 获取页数
    # author = Author.objects.get()
    article_list = Article.objects.all()
    p = Paginator(article_list, page_num)
    try:
        a_list = p.page(page)
    except PageNotAnInteger:
        # 如果请求的页面不是整数,返回第一页
        a_list = p.page(1)
    except EmptyPage:
        # 如果请求的页面不在合法的页数范围内,返回结果的最后一页
        a_list = p.page(paginator.num_pages)
        print(p.num_pages)
    # return render(request, "news/fabu.html", {"author_list": a_list, 'page': page})
    return a_list


# 我的发布认证
def news_list(request):
    username = request.session.get('user', default=False)
    if username != False:
        if 'status' in request.GET:
            status = request.GET['status']
            article_list = Article.objects.filter(
                status=status).values() if status != '0' else Article.objects.all().values()
            response = JsonResponse(list(article_list),safe=False)
            response.set_signed_cookie('status', str(status), salt='wenyong')
            return response





# 发布验证
def fbyz(request):
    username = request.session.get('user', default=False)
    if username != False:
        if request.method == 'POST':
            if Author.objects.filter(username=username).exists():
                author = Author.objects.get(username=username)
                print('============')
                article = Article()
                article.title = request.POST['title']
                article.categroy_id = request.POST['class']
                article.author_id = author.id
                article.source = request.POST['source']
                article.digist = request.POST['digist']
                article.image = request.FILES['pic']
                article.content = request.POST['content'].len()
                article.save()
                return render(request, 'news/fbcg.html', {'author': author})
            else:
                return HttpResponse('有黑客入侵,请加固网络')
        else:
            return HttpResponse('有黑客入侵,请加固网络')
    else:
        error_info = '用户不是本人!重新输入'
        return render(request, 'news/fbnr.html', {'error_info': error_info})



# 发布内容
def fbnr(request):
    username = request.session.get('user', default=False)
    if username is False:
        return redirect('news:login')
    else:
        if Author.objects.filter(username=username).exists():
            author = Author.objects.get(username=username)
            if request.method == 'POST':
                pass
            form =EditorForm
            return render(request,'news/fbnr.html',{'author':author,'form':form})


# 发布成功
def fbcg(request):
    username = request.session.get('user')
    author = Author.objects.get(username=username)
    return render(request, 'news/fabu.html',{'author': author})





# 积分
def jifen(request):
    username = request.session.get('user', default=False)
    if username == False:
        author = Author.objects.get(username=username)
        status = request.get_signed_cookie('status', salt='wenyong', default=None)

        return render(request, 'news/jifen.html')
    else:
        if Author.objects.filter(username=username).exists():
            author = Author.objects.get(username=username)
            bill = Bill.objects.filter(author=author.id)

            # 分页
            bills_list = author.bills.all()
            page = request.GET.get('page')
            page_yeshu = 10
            contacts = page_aduit(bills_list,page, page_yeshu)
            # print(bill)
            if request.method == "POST":
                jifen = request.POST['jifen']
                score = author.score
                author.score = score - int(jifen)*10000
                if author.score > 0:
                    author.leave_count = author.leave_count + int(jifen)
                    author.save()
                    info = '尊敬的用户' + author.username + ',您成功减积分:' + jifen
                    return redirect('news:people')
                else:
                    return redirect('news:hy')
            else:
                # error_info = '添加失败,请检查操作步骤,重新操作!!!'
                return render(request, 'news/jifen.html', {'author': author, 'bills':bill,'contacts':contacts})


# 积分兑换
def jfdh(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        return render(request, 'news/jfdh.html', {'author': author,})


# 积分兑换验证,发布文章减积分
def reduce_jf(request):
    username = request.session.get('user', default=False)
    if username == False:
        return render(request, 'news/base.html')
    else:
        author = Author.objects.get(username=username)
        if author.score / 1000 == 0:
            now = datetime.now()
            now = now.strftime("%Y-%m-%d %H:%M")
            info = '尊敬的用户您好!截止到' + now + "为止, 您的积分已经消费完,请充值!!"
            return render(request, 'news/hy.html', {"author":author, 'info':info})
        else:
            if request.mothod == "POST":
                article = Article()
                article.title = request.POST['title']
                article.score = request.POST['score']
                article.content = request.POST['content']
                article.save()
                author.score -= 1000
                article_list = Article.objects.filter(author=author).values()
                author.save()
                return render(request, 'news/jifen.html', {'author':author})
            return HttpResponse('输入操作有误!!!!,请重新输入')


# 退出登录

def log_out(request):
    logout(request)
    return HttpResponseRedirect(reverse('news:log'))


# 显示编辑器
def editor(request):
    return render(request, 'news/editor.html')




# 新闻首页
def base_news(request):
    # if request.method == "GET":
    username = request.session.get('user', default=False)
    author = Author.objects.get(username=username)
    a = request.get_signed_cookie('a', salt='xiaoli', default=None)
    if username != False:
        type = request.GET.get('type')
        request.session['type'] = type
        print(type)
        if 'type' in request.GET:
            # 内容
            article_list = Article.objects.filter(categroy_id=type)[0:1]
            # 快讯
            ar_list = Article.objects.all()[:4]
            # 热门新闻
            art_list = Article.objects.order_by('id')[:5]
            return render(request, 'news/base_news.html',{'author': author,'article_list':article_list,'art_list': art_list,'ar_list':ar_list})
        else:
            # 内容
            article_list = Article.objects.all()[0:5]
            # 快讯
            ar_list = Article.objects.all()[:4]
            # 热门新闻
            art_list = Article.objects.order_by('id')[:5]
            return render(request, 'news/base_news.html',{'author': author, 'article_list': article_list, 'art_list': art_list, 'ar_list': ar_list})
    return HttpResponse(234567)


# 加载更多
def base_news_ajax(request):
    a = request.GET.get('status')
    type = request.session.get('type')
    if type is None:

        # 内容
        article_list = Article.objects.all().order_by('distribute_time')[0:(5+int(a))].values('title','image', 'content','digist', 'distribute_time')
        response = JsonResponse(list(article_list), safe=False)
        response.set_signed_cookie('a', str(a), salt='xiaoli')
        return response
    else:
        # 内容
        article_list = Article.objects.filter(categroy_id=type).order_by('distribute_time', '' 'votes_count')[0:(1 + int(a))].values('title', 'image','content','digist','distribute_time','share_count', 'votes_count')
        response = JsonResponse(list(article_list), safe=False)
        response.set_signed_cookie('a', str(a), salt='xiaoli')
        return response


# 新闻详情
def news_xq(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        # 点赞
        new = request.GET.get('news_id', False)
        new_art = Article.objects.get(id=new)
        new_art.votes_count += 1
        new_art.save()
        # 热门新闻
        art_list = Article.objects.all()

        return render(request, 'news/news_xq.html', {'author': author,'new_art':new_art,'art_list': art_list})
    else:
        return render(request, 'news/base_news.html')

# 点赞
def dz(request):
    if request.method=='POST':
        data = json.loads(request.body.decode('utf-8'))
        username = request.session.get('user')
        author = Author.objects.get(username=username)
        Bill.objects.create(title='分享文章', author=author)
        try:
            art = Article.objects.get(id=int(data['new_art_id']))
            x = data['num']
            if x == 1:
                art.view_count += 1
                art.save()
                return HttpResponse(str(art.view_count))
            elif x == 2:
                art.share_count += 1
                art.save()
                return HttpResponse(str(art.share_count))
        except Exception as e:
            return HttpResponse('error')


 # 新闻快讯
def news_kx(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        art_list = Article.objects.all()
        return render(request, 'news/news_kx.html',locals())
    return render(request, 'news/base_news.html')


# 快讯详情
def news_kxxq(request):
    username = request.session.get('user', default=False)
    if username != False:
        author = Author.objects.get(username=username)
        page = request.GET.get('page', False)
        page = page if page != False else 1
        # 内容
        art_list = Article.objects.all()
        new = request.GET.get('news_id')
        new_art = Article.objects.get(id=new)
        new_art.votes_count += 1
        new_art.save()
        return render(request, 'news/news_kxxq.html', {'author': author,'art_list':art_list,'new_art':new_art,})


# 消息通知
def xxtz(request):
    username = request.session.get('user', default=False)
    if username == False:
        return redirect('news:log')
    else:
        # aut = request.POST.get('ca')
        if Author.objects.filter(username=username).exists():
            author = Author.objects.get(username=username)
            page1 = author.comments.all()
            page = request.GET.get('page')
            page_yeshu = 10
            contacts = page_aduit( page1,page, page_yeshu)
            return render(request, 'news/xxtz.html', {'author': author, 'contacts':contacts})


# # 发表评论
@csrf_exempt
def comm(request):
    username = request.session.get('user', default=False)
    if username == False:
        return redirect('news:log')
    else:
        id = request.POST.get('ca')
        id = int(id)
        if Article.objects.filter(id=id).exists():
            content = request.POST.get('content')
            author = Author.objects.get(username=username)
            Comment.objects.create(content=content,article_id=id, author=author)
            return JsonResponse({'suce':'评论成功'})
        else:
            return JsonResponse({'suce': '评论失败'})


# 判断审核状态
def page_aduit(article_list, page, page_yeshu):
    paginator = Paginator(article_list, page_yeshu)
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果请求的页数不是整数，返回第一页。
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
        contacts = paginator.page(paginator.num_pages)
    return contacts